import django
from django import http
from django import shortcuts

from google.appengine.api import images
from google.appengine.api import memcache

from blog.models import *
from blog.helper import *
from blog.sql import *
from blog.sessions import *
from conf.settings import *
 
def list(request):
    params = {}
    where = ""
    now = datetime.datetime.now()
    
    cate_id = SafeGet('cate_id', None, request)
    date = SafeGet('date', None, request)
    
    
    if cate_id:
        vCate = VCate.get_by_id(int(cate_id))
        items = vCate.articles
        #q.order("-created")   
        items = items.fetch(50)
    else:
        cacheItems = "list_article"
        if date is None:
            items = memcache.get(cacheItems)
            if items is None:
                q = VArticle.all()
                q.order("-created")
                items = q.fetch(10)
                memcache.set(cacheItems, items, 1000)
        else:
            date = DateTimeRealToDB(date)
            q = VArticle.all()
            q.filter("created <", date)
            q.order("-created")
            items = q.fetch(10)

    
    #items = VArticle.gql("WHERE " + where + " created < :1  ORDER BY created DESC LIMIT 10",date)
    #items = VArticle.gql("WHERE  status=1 " + where + " ORDER BY created DESC")
    
    #items = VArticle.all()
    pageDate = now
    if items:
        for item in items:
            if item.created < pageDate:
                pageDate = item.created
    params['Title'] = 'Blog 090' 
    params['items'] = items
    params['pageDate'] = pageDate
    return respond(request, None, 'varticle_list', params)

def listAjax(request):
    params = {}
    where = ""
    now = datetime.datetime.now()
    
    cate_id = SafeGet('cate_id', None, request)
    date = SafeGet('date', None, request)
    
    
    if cate_id:
        vCate = VCate.get_by_id(int(cate_id))
        items = vCate.articles
        #q.order("-created")   
        items = items.fetch(50)
    else:
        cacheItems = "list_article"
        if date is None:
            items = memcache.get(cacheItems)
            if items is None:
                q = VArticle.all()
                q.order("-created")
                items = q.fetch(10)
                memcache.set(cacheItems, items, 10000)
        else:
            date = DateTimeRealToDB(date)
            q = VArticle.all()
            q.filter("created <", date)
            q.order("-created")
            items = q.fetch(10)

    
    #items = VArticle.gql("WHERE " + where + " created < :1  ORDER BY created DESC LIMIT 10",date)
    #items = VArticle.gql("WHERE  status=1 " + where + " ORDER BY created DESC")
    
    #items = VArticle.all()
    pageDate = now
    if items:
        for item in items:
            if item.created < pageDate:
                pageDate = item.created
    params['Title'] = 'Blog 090' 
    params['items'] = items
    params['pageDate'] = pageDate
    return respond(request, None, 'varticle_list_ajax', params)

def delete(request, idItem):
    member = Permission(1)
    item = None
    if idItem:
        item = VArticle.get_by_id(int(idItem))
        if item is None:
            return http.HttpResponseNotFound('No Item')
        else:
            if isAdmin() is None:
                if item.member.user != member.user:
                    return respond(request, None, 'message_box', {"message":"No Permission."})
    item.delete()
    return http.HttpResponseRedirect('/varticle')

def add(request):
    return edit(request, None)

def edit(request, idItem):
    member = Permission(1)
        
    params = {}
    params['Title'] = 'Add / Edit Article'
    
    item = None
    if idItem:
        item = VArticle.get_by_id(int(idItem))
        if item is None:
            return http.HttpResponseNotFound('No Item')
        else:
            if isAdmin() is None:
                if item.member.user != member.user:
                    return respond(request, None, 'message_box', {"message":"No Permission."})
    # Cate Option
    optionCate = ListOptionCate(0,'==',None,True)
    params['optionCate'] = optionCate
        
    params['item'] = item
    
    if not request.POST:
        return respond(request, None, 'varticle_edit', params)
  
    if item is None:
        item = VArticle()
    if request.FILES:
        img_data    = request.FILES['image']['content']
        img         = images.Image(img_data)
        img.im_feeling_lucky()
        img.resize(150, 150)
        img_data    = img.execute_transforms(images.PNG)
        item.image  = img_data 
    try:            
        item.title      = unicode(SafePost('title', '', request), 'utf-8')
        item.link       = SafePost('link',None, request)
        item.status     = int(SafePost('status', 0, request))
        item.scontent   = unicode(SafePost('scontent', '', request), 'utf-8')
        item.content    = unicode(SafePost('content', '', request), 'utf-8')
        if item.member is None:
            item.member     = member
            item.member_name= member.name 
            item.member_id  = member.key().id()
        #Cate
        cate = VCate.get_by_id(int(SafePost('cate', None, request)))
        if cate:
            item.cate       = cate
            item.cate_id    = int(cate.key().id())
        
    except db.Error, err:
        params['err'] = err
        params['item'] = item
        return respond(request, None, 'varticle_edit', params)
  
    item.put()
    #Insert Chat
    #chat = VChat()
    #chat.scontent   = "<a target='_blank' href='/varticle/view/"+str(item.key().id())+"'>"+item.title+"</a><br>"
    #chat.member     = member
    #chat.member_name= member.name 
    #chat.member_id  = member.key().id()
    #chat.put()

    return http.HttpResponseRedirect('/view/'+str(item.key().id()))

def view(request, idItem):
    params = {}
    params['Title'] = 'View Article'
    item = None
    if idItem:
        cacheItem = "article"+idItem
        item = memcache.get(cacheItem)
        if item is None:
            item = VArticle.get_by_id(int(idItem))
            memcache.set(cacheItem, item, 10000)

        if item:
            params['item'] = item
            item.hit = item.hit + 1
            params['Title'] = unicode(item.title)# + ' - [ ' + str(item.hit) + ' ]'
#            item.put()
        return respond(request, None, 'varticle_view', params)
    else:
        return respond(request, None, 'message_box', {"message":"No Article."})

def image(request,idItem):
#    if idItem:
#        cacheItem = "article"+idItem
#        item = memcache.get(cacheItem)
#        if item is None:
#            item = VArticle.get_by_id(int(idItem))
#            item = item
#            memcache.set(cacheItem, item, 10000)
#        if item.image:
#            return http.HttpResponse(item.image,mimetype='image/png')
    return  http.HttpResponse('')
